package com.atguigu.PracticalProject.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.PracticalProject.app.BaseAppV1;
import com.atguigu.PracticalProject.common.Constant;
import com.atguigu.PracticalProject.util.AtguiguUtil;
import com.atguigu.PracticalProject.util.FlinkSinkUtil;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.HashMap;
import java.util.Map;

public class DwdBaseLogApp extends BaseAppV1 {
    public static void main(String[] args) {
        new DwdBaseLogApp().init(
                3013,
                2,
                "DwdBaseLogApp",
                Constant.TOPIC_ODS_BASE_LOG
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        //etl
        SingleOutputStreamOperator<JSONObject> etledStream = etl(stream);
        //2.纠正新老用户标签
        SingleOutputStreamOperator<JSONObject> validatedStream = validateNewOrOld(etledStream);
        //3.分流
        Map<String, DataStream<JSONObject>> stringDataStreamMap = splitStream(validatedStream);
        //写到kafka
        writeToKafka(stringDataStreamMap);
    }

    private void writeToKafka(Map<String, DataStream<JSONObject>> stringDataStreamMap) {
        stringDataStreamMap.get(Constant.START).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
        stringDataStreamMap.get(Constant.ACTION).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTION));
        stringDataStreamMap.get(Constant.ERR).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
        stringDataStreamMap.get(Constant.PAGE).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));
        stringDataStreamMap.get(Constant.DISPLAY).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAY));
    }

    private Map<String, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> validatedStream) {
        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>("display") {};
        OutputTag<JSONObject> actionTag = new OutputTag<JSONObject>("action") {};
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>("page") {};
        OutputTag<JSONObject> errTag = new OutputTag<JSONObject>("err") {};
        SingleOutputStreamOperator<JSONObject> allStream = validatedStream
                .process(new ProcessFunction<JSONObject, JSONObject>() {
                    @Override
                    public void processElement(JSONObject obj,
                                               Context ctx,
                                               Collector<JSONObject> out) throws Exception {
                        if (obj.containsKey("start")) {
                            //启动日志
                            out.collect(obj);
                        } else {
                            JSONObject common = obj.getJSONObject("common");
                            JSONObject page = obj.getJSONObject("page");
                            Long ts = obj.getLong("ts");
                            JSONArray displays = obj.getJSONArray("displays");
                            if (displays != null) {
                                for (int i = 0; i < displays.size(); i++) {
                                    JSONObject display = displays.getJSONObject(i);
                                    display.putAll(common);
                                    display.putAll(page);
                                    display.put("ts", ts);
                                    ctx.output(displayTag, display);
                                }
                                obj.remove("displays");
                            }
                            JSONArray actions = obj.getJSONArray("actions");
                            if (actions != null) {
                                for (int i = 0; i < actions.size(); i++) {
                                    JSONObject action = actions.getJSONObject(i);
                                    action.putAll(common);
                                    action.putAll(page);
                                    ctx.output(actionTag, action);
                                }
                                obj.remove("actions");
                            }
                            if (obj.containsKey("err")) {
                                ctx.output(errTag, obj);
                                obj.remove("err");
                            }
                            if (page != null) {
                                ctx.output(pageTag, obj);
                            }
                        }
                    }
                });
        Map<String, DataStream<JSONObject>> fiveStream = new HashMap<>();
        fiveStream.put(Constant.START,allStream);
        fiveStream.put(Constant.DISPLAY,allStream.getSideOutput(displayTag));
        fiveStream.put(Constant.ACTION,allStream.getSideOutput(actionTag));
        fiveStream.put(Constant.ERR,allStream.getSideOutput(errTag));
        fiveStream.put(Constant.PAGE,allStream.getSideOutput(pageTag));
        return fiveStream;
    }

    private SingleOutputStreamOperator<JSONObject> validateNewOrOld(SingleOutputStreamOperator<JSONObject> etledStream) {
        return etledStream
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .map(new RichMapFunction<JSONObject, JSONObject>() {

                    private ValueState<String> firstVisitDate;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        firstVisitDate = getRuntimeContext().getState(new ValueStateDescriptor<String>("firstVisitDate", String.class));
                    }

                    @Override
                    public JSONObject map(JSONObject obj) throws Exception {
                        JSONObject common = obj.getJSONObject("common");
                        //取出状态
                        String firstVisit = firstVisitDate.value();
                        Long ts = obj.getLong("ts");
                        String today = AtguiguUtil.toDate(ts);

                        //标签可能有误，需要修改
                        if ("1".equals(common.getString("is_new"))) {
                            //标签为1 新用户 状态为null
                            if (firstVisit == null) {
                                //确实是第一次，不需要该，但是需要更新状态
                                firstVisitDate.update(today);
                            } else if (!today.equals(firstVisit)) {
                                common.put("is_new",0);
                            }
                        } else {
                            // 标签是老用户，状态是空
                            // 意味着，用户曾经访问过，但是程序中没有记录着一条
                            // 把状态更新成昨天
                            if (firstVisit == null) {
                                String yesterday = AtguiguUtil.toDate(ts - (24 * 60 * 60 * 1000));
                                firstVisitDate.update(yesterday);
                            }
                        }
                        return obj;
                    }
                });
    }

    private SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> stream) {
        return stream
                .filter(json -> {
                    try {
                        JSON.parseObject(json);
                    } catch (Exception e) {
                        System.out.println("json格式有误，经检查：" + json);
                        return false;
                    }
                    return true;
                })
                .map(JSON::parseObject);
    }
}
